
from fastapi import APIRouter,HTTPException
from starlette import status
import jwt
from fastapi.security import OAuth2PasswordBearer,OAuth2PasswordRequestForm

from backend.app.app.core.config import auth_password,auth_username
from backend.app.app.api.utils.encryption import rsa_decrypt
from backend.app.app import rsa_private_key
from backend.app.app.crud_sys.tb_license import all_tblicense,add_newlegalperson,license_update,license_del,all_id
from backend.app.app.models.user import name_pwd
from backend.app.app.models.license import save_lib
from backend.app.app.api.api_v1.user import token1
from backend.app.app.api.api_v1.use_token import create_access_token,Depends,turn_exp,SECRET_KEY,ALGORITHM
from backend.app.app.crud_sys.tb_user import get_all_online

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api_v1/auth/login")

auth_router = APIRouter(prefix="/auth", tags=["开发商"])
save_auth_token = ""     #记录token
Auth_token_efficient_time = 30      #令牌有效时间
Judge_toke_refresh = 10

# 验证当前开发商令牌         (tokenUrl="/api_v1/auth/login")
async def verify_token_auth(token: token1):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    token = token.token_data
    try:
        #验证令牌用户名，有效性，有效期
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        global save_auth_token
        username: str = payload.get("sub")
        # 判断身份是否为开发商
        if payload.get("user_status") == "auth":
            raise credentials_exception
        # 判断令牌是否可用
        save_auth_token = jwt.decode(save_auth_token, SECRET_KEY, algorithms=[ALGORITHM])
        if save_auth_token.get("iat") != payload.get("iat"):
            raise credentials_exception
        save_auth_token = jwt.encode(save_auth_token, SECRET_KEY, algorithm=ALGORITHM)
        if username is None:
            raise credentials_exception
        #判断令牌是否过期
        start = payload.get("iat")
        end = turn_exp()
        if (end-start)/60 >= Auth_token_efficient_time:
            raise credentials_exception
    except :
        raise credentials_exception

    if (end - start)/60 > Judge_toke_refresh:
        #之前的令牌作废
        #创立新的令牌并返回
        print("new")
        access_token = create_access_token(data={"sub": username}, expires_delta=Auth_token_efficient_time, avai=True,user_status="auth")
        save_auth_token = access_token   #更新令牌
        return {"access_token": access_token, "token_type": "bearer","user":username,"new":True}
    else:
        return {"user":username,"new":False}

@auth_router.post("/get_online",name="获取在线人数")
async  def get_online():
    a = get_all_online()
    b = len(a)
    return {"online_num":b}

#开发商登录
@auth_router.post("/login",name="开发商登录")
#name_pwd:name_pwd          OAuth2PasswordRequestForm = Depends()
async def auth_login(name_pwd:name_pwd):
    if name_pwd.username == auth_username:
        front_pwd = rsa_decrypt(name_pwd.password,rsa_private_key)
        print(front_pwd)
        # front_pwd = name_pwd.password
        if front_pwd == auth_password:
            access_token = create_access_token(data={"sub": name_pwd.username},expires_delta=30,avai=True,user_status="auth")
            global  save_auth_token
            save_auth_token = access_token
            return {"username":True,"password":True,"access_token":access_token, "token_type": "bearer"}
        else:
            return {"username": True, "password": False}
    else:
        return {"username": False, "password": False}

#开发商读库
@auth_router.post("/read_lib",name="读库")
async def read_lib(ver = Depends(verify_token_auth)):
    try:
        all_count = all_tblicense()
        return {"lib":all_count,"verify":ver}

    except:
        return {"lib":False,"verify":ver}

#开发商存库
@auth_router.post("/save_lib",name="存库")
async def save_lib(auth_save:save_lib,ver = Depends(verify_token_auth)):
    print(auth_save)
    a = False
    b = False
    c = False
    # 新增部分  add
    for i in auth_save.add:
        fff = all_id()
        print(fff)
        fff = len(fff) + 1
        print(i)
        a = add_newlegalperson(legalperson_id=fff,  #实现id自增
                           legalperson_name=i['legalperson_name'],
                           legalperson_code=i['legalperson_code'],
                           legalperson_representative=i['legalperson_representative'],
                           auth_serial_number=i['auth_serial_number'],
                           authed_stardate=i['authed_stardate'],
                           authed_enddate=i['authed_enddate'],
                           user_db_constr=i['user_db_constr'],
                           authed_online_number=i['authed_online_number'],
                           isqualified=i['isqualified'],
                           license_remarks=i['license_remarks'],
                           auth_devname=i['auth_devname']
                           )
    #删除部分   delete
    for j in auth_save.delete:
        if j:
            b = license_del(j)
    #修改部分   modify
    for k in auth_save.modify:
        if k:
            m = []
            for item in k.keys():
                m.append(k[item])
            c = license_update(m)
    return {"add":a,  "modify":c,"delete":b,"verify":ver}
